package com.ftg.learn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ftg.learn.entity.sys.User;
import com.ftg.learn.entity.sys.UserRole;
import com.ftg.learn.mapper.UserMapper;
import com.ftg.learn.mapper.UserRoleMapper;
import com.ftg.learn.service.Iuser;
import com.ftg.learn.util.MD5;
import com.ftg.learn.util.ResultJson;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.List;
import java.util.Objects;

/**
 * @author kangjx
 * @createTime 2022/10/21
 */
@Service
public class IuserImpl extends ServiceImpl<UserMapper,User> implements Iuser {

    // 密码学  最简单的加密 jwt : json web token [对称加密 des  和非对称加密 rsa]

//    md5 :

    @Resource
    UserMapper userMapper;

    @Resource
    UserRoleMapper userRoleMapper;

    @Override
    public ResultJson loginForUser(String account, String password) {

        password = MD5.encrypt2ToMD5(password);

        User userInfo = userMapper.loginForUser(account,password);
        if(Objects.isNull(userInfo)){
            return ResultJson.FAILURE();
        }
        return ResultJson.OK(userInfo);
    }

    @Override
    public ResultJson showProvilegeWithUid(int uid) {
        return ResultJson.OK(userMapper.showProvilegeWithUid(uid));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultJson giveRoleForUser(int uid, List<Integer> rids) {
        QueryWrapper<UserRole> query = new QueryWrapper<>();
        query.eq("u_id",uid);
        //删除 原来的所有角色
        userRoleMapper.delete(query);

        for (Integer rid : rids) {
            UserRole userRole = new UserRole();
            userRole.setUid(uid);
            userRole.setRid(rid);
            userRoleMapper.insert(userRole);
        }
        return ResultJson.OK(null);
    }

}
